<?php

namespace app\admin\controller\shop\user;

use app\admin\controller\shop\Base;
use app\shop\enums\user\UserMoneyChangeType;
use think\db\exception\DbException;
use Throwable;

/**
 * 用户余额管理
 */
class MoneyLog extends Base
{
    /**
     * MoneyLog模型对象
     * @var object
     * @phpstan-var \app\admin\model\shop\user\MoneyLog
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['user.nickname'];

    protected array $withJoinTable = ['user' => ['username', 'nickname']];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\shop\user\MoneyLog;
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    /**
     * 列表
     * @return void
     * @throws Throwable
     * @throws DbException
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        $types = UserMoneyChangeType::getAllDescriptions();

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
            'types'  => $types,
        ]);
    }

    /**
     * 添加
     * @param int $userId
     */
    public function add(int $userId = 0): void
    {
        if ($this->request->isPost()) {
            parent::add();
        }

        $user = \app\admin\model\shop\user\User::where('id', $userId)->findOrEmpty();
        if ($user->isEmpty()) {
            $this->error(__("The user can't find it"));
        }
        $this->success('', [
            'user' => $user
        ]);
    }
}